<template>
    <div>
      <div class="crumbs">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item
          v-for="(item,index) in breadList"
          :key="index"
          :to="{ path: item.path }"
        >{{item.meta.title}}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="container">
        <div>
          <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" status-icon>
            <el-form-item label="景点名" prop="name">
              <el-input v-model="ruleForm.name" />
            </el-form-item>
            <el-form-item label="景点简介" prop="desc">
              <el-input v-model="ruleForm.desc" type="text" />
            </el-form-item>
            <el-form-item label="开放时间" prop="opentime">
              <el-input v-model="ruleForm.opentime" type="time"/>
            </el-form-item>
            <el-form-item label="景点地址" prop="address">
              <el-input v-model="ruleForm.address"/>
            </el-form-item>
            <el-form-item label="图片" prop="img">
              <button @click="uploadimg">上传所有图片</button>
              <mavon-editor v-model="ruleForm.img" style="width: 100%;" ref="md" @imgAdd="imgAdd" @imgDel="imgDel" />
            </el-form-item>
            <el-form-item label="景点类型" prop="type">
              <el-radio-group v-model="ruleForm.type">
                <el-radio :label="0">自然景点</el-radio>
                <el-radio :label="1">文化景点</el-radio>
                <el-radio :label="2">主题公园</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </div>
        <div>
          <el-button type="primary" @click="submitForm(ruleFormRef)">新增</el-button>
            <el-button @click="resetForm(ruleFormRef)">重置表单</el-button>
        </div>
      </div>
    </div>
  </template>
  <script>
  import { useRouter, useRoute } from 'vue-router'
  import { ref, reactive, watch } from "vue";
  import request from "../../utils/request";
  import { ElNotification } from "element-plus";
  export default {
    setup() {
      let breadList = [] // 路由集合
      const route = useRoute()
      const getBreadcrumb=(url)=> {
        let matched = url.matched;
        //如果不是首页
        if ("Home"==matched[0].name) {
          matched[0].meta =  { title: "系统首页" } 
        }
        breadList = matched;
      }
      watch(route, (newValue, oldValue) => {
        // console.log(222222,newValue)
        getBreadcrumb(newValue)
      },{ deep: true, immediate: true });
      
      const resetForm = (formEl) => {
        if (!formEl) return;
        formEl.resetFields();
      };
      const submitForm = async (formEl) => {
        if (!formEl) return;
        await formEl.validate((valid, fields) => {
          if (valid) {
            // console.log("提交更新", fields);
            request
              .request({
                url: "/attraction/add",
                method: "post",
                data: {
                  name: ruleForm.name,
                  desc: ruleForm.desc,
                  type: ruleForm.type,
                  opentime: ruleForm.opentime,
                  address:ruleForm.address,
                  img: ruleForm.img,
                },
              })
              .then((res) => {
                if (res.data.code == 200) {
                  ElNotification({
                    title: "更新成功",
                    message: "成功更新用户信息",
                  });
                } else {
                  ElNotification({
                    title: "更新失败",
                    message: "请联系管理员检查失败原因",
                  });
                }
              })
              .catch((e) => {
                ElNotification({
                  title: "更新失败",
                  message: "请联系管理员检查失败原因",
                });
              });
          } else {
            ElNotification({
              title: "校验失败",
              message: "请重新填写信息",
            });
          }
        });
      };
      const ruleForm = reactive({
        id: "",
        name: "",
        desc: "",
        img: "",
        type: "",
      });
      const rules = reactive({
        name: [
          {
            required: true,
            message: "景点名",
            trigger: "blur",
          },
        ],
        desc: [
          {
            required: true,
            message: "请输入简介",
            trigger: "blur",
          },
        ],
        opentime: [
          {
            required: true,
            message: "请输入开放时间",
            trigger: "blur",
          },
        ],
        type: [
          {
            required: true,
            message: "请选择用户类型",
            trigger: "change",
          },
        ],
        img: [
          {
            required: true,
            message: "请选择图片",
            trigger: "change",
          },
        ],
      });
      const ruleFormRef = ref();
      const centerDialogVisible = ref(false);
      let md = ref(null)
    let img_file = {}
    const imgAdd = (pos, $file) => {
      // 缓存图片信息
      img_file[pos] = $file;
    }
    const imgDel = (pos) => {
      delete img_file[pos];
    }
    const uploadimg = ($e) => {
      // 第一步.将图片上传到服务器.
      var formdata = new FormData();
      for (var _img in img_file) {
        formdata.append('files', img_file[_img]);
      }
      request.request({
        url: '/attraction/imageAdd',
        method: 'post',
        data: formdata,
        headers: { 'Content-Type': 'multipart/form-data' },
      }).then((res) => {
        const paths = res.data.data.payload
        /**
         * 例如：返回数据为 res = [[pos, url], [pos, url]...]
         * pos 为原图片标志（0）
         * url 为上传后图片的url地址
         */
        // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
        for(let index=0;index<paths.length;index++){
          md.value.$img2Url(index+1, paths[index]);
        }
      })
    }
      return {
        breadList,
        resetForm,
        ruleFormRef,
        submitForm,
        ruleForm,
        rules,
        centerDialogVisible,
        uploadimg,
        imgDel,
        imgAdd,
        md,
      };
    },
  };
  </script>
  <style lang="scss" scoped>
  .handle-box {
    margin-bottom: 20px;
  }
  
  .handle-select {
    width: 120px;
  }
  
  .handle-input {
    width: 300px;
    display: inline-block;
  }
  
  .table {
    width: 100%;
    font-size: 14px;
  }
  
  .red {
    color: #ff0000;
  }
  
  .mr10 {
    margin-right: 10px;
  }
  
  .table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
  }
  </style>
  